{% extends "themes/" + sysSettings.systemTheme + "/layout.html" %}

{% block head %}
<title>{{sysSettings.siteName}} - Administration Page</title>

<script type="text/javascript" src="/static/vendor/socketio/js/socket.io.js"></script>
<script type="text/javascript" src="/static/vendor/chartjs/js/Chart.bundle.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/vendor/datatables/css/datatables.css"/>

{% endblock %}

{% block body %}
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-lg-10 col-md-12" style="margin-top:15px;">
            <ul class="nav nav-pills mb-3" id="admin-nav" role="tablist">
                <li class="nav-item">
                    <a class="nav-link {% if page == None or page == 'dash' %} active {% endif %}"  role="tab" id="admin-nav-dashboard" href="#dashboard" data-toggle="pill" aria-controls="admin-nav-dashboard" aria-selected="true">Dashboard</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'settings' %} active {% endif %}" role="tab" id="admin-nav-settings" href="#adminSettings" data-toggle="pill" aria-controls="admin-nav-settings" aria-selected="false">Settings</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'oauth' %} active {% endif %}" role="tab" id="admin-nav-oauth" href="#adminOauth" data-toggle="pill" aria-controls="admin-nav-oauth" aria-selected="false">OAuth Providers</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'ospedge' %} active {% endif %}" role="tab" id="admin-nav-edge" href="#edgeSettings" data-toggle="pill" aria-controls="admin-nav-edge" aria-selected="false">Edge Streamers</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'webhooks' %} active {% endif %}" role="tab" id="admin-nav-webhooks" href="#webhooksSettings" data-toggle="pill" aria-controls="webhooks-nav-settings" aria-selected="false">Webhooks</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'users' %} active {% endif %}" role="tab" id="admin-nav-users" href="#userList" data-toggle="pill" aria-controls="admin-nav-users" aria-selected="false">Users</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'topics' %} active {% endif %}" role="tab" id="admin-nav-topics" href="#topicsList" data-toggle="pill" aria-controls="admin-nav-topics" aria-selected="false">Topics</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'channels' %} active {% endif %}" role="tab" id="admin-nav-channels" href="#channelsList" data-toggle="pill" aria-controls="admin-nav-channels" aria-selected="false">Channels</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'streams' %} active {% endif %}" role="tab" id="admin-nav-streams" href="#streamsList" data-toggle="pill" aria-controls="admin-nav-streams" aria-selected="false">Streams</a>
                </li>
                {# <li class="nav-item">
                    <a class="nav-link {% if page == 'hub' %} active {% endif %}" role="tab" id="admin-nav-hub" href="#hubSettings" data-toggle="pill" aria-controls="admin-nav-hub" aria-selected="false">Hub</a>
                </li> #}
                <li class="nav-item">
                    <a class="nav-link {% if page == 'logs' %} active {% endif %}" role="tab" id="admin-nav-logs" href="#logs" data-toggle="pill" aria-controls="admin-nav-logs" aria-selected="false">Logs</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link {% if page == 'backup' %} active {% endif %}" role="tab" id="admin-nav-backuprestore" href="#backuprestore" data-toggle="pill" aria-controls="admin-nav-backuprestore" aria-selected="false">Backup/Restore</a>
                </li>
            </ul>

            <div class="tab-content" id="admin-content">
                <div class="tab-pane fade {% if page == None or page == 'dash' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-dashboard" id="dashboard">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-lg-6 col-md-12">
                                <div>
                                    <h2><i class="fas fa-server"></i> Server Info</h2><br>
                                    <b><img src="/static/img/logo.png" width="64px" height="64px"> Open Streaming Platform</b><br>
                                    <div style="margin-left:70px;">
                                        <b><a href="https://gitlab.com/Deamos/flask-nginx-rtmp-manager">https://gitlab.com/Deamos/flask-nginx-rtmp-manager</a></b><br>
                                        <b>Server Version:</b> {{sysSettings.version}} <br>
                                        <b>Git Branch:</b> {{repoBranch}} <br>
                                        <b>Git Commit Hash:</b> {{repoSHA}}  {% if repoSHA != remoteSHA %} <span class="badge badge-success">Update Available!</span> {% else %} <span class="badge badge-secondary">No Update Available</span>{% endif %}<br>
                                        <b>Database Version:</b> {{appDBVer}} <br><br>
                                        <b>NGINX Version:</b> {{nginxStatData['rtmp']['nginx_version']}}<br>
                                        <b>NGINX-RTMP Version</b> {{nginxStatData['rtmp']['nginx_rtmp_version']}}<br>
                                        <b>Uptime:</b> {{nginxStatData['rtmp']['uptime']|hms_format}}
                                    </div>
                                </div><br>
                                <div class="card">
                                    <div class="card-header"><i class="fas fa-video"></i> <a href="/settings/admin/rtmpstat/localhost">RTMP Stats</a></div>
                                    <div class="card-body">
                                        <table class="table table-hover">
                                            <thead>
                                            <tr>
                                                <th scope="col">Endpoint</th>
                                                <th scope="col">Key</th>
                                                <th scope="col">In Kbps</th>
                                                <th scope="col">Out Kbps</th>
                                                <th scope="col">Clients</th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            {% for data in nginxStatData['rtmp']['server']['application'] %}
                                                {% if 'stream' in data['live'] %}
                                                    {% if data['live']['stream'] | testList %}
                                                        {% for entry in data['live']['stream'] %}
                                                            <tr>
                                                                <td>{{data['name']}}</td>
                                                                <td>{{entry['name']}}</td>
                                                                <td>{{entry['bw_in']|format_kbps}}</td>
                                                                <td>{{entry['bw_out']|format_kbps}}</td>
                                                                <td>{{entry['client']|processClientCount}}</td>
                                                            </tr>
                                                        {% endfor %}
                                                    {% else %}
                                                    <tr>
                                                        <td>{{data['name']}}</td>
                                                        <td>{{data['live']['stream']['name']}}</td>
                                                        <td>{{data['live']['stream']['bw_in']|format_kbps}}</td>
                                                        <td>{{data['live']['stream']['bw_out']|format_kbps}}</td>
                                                        <td>{{data['live']['stream']['client']|processClientCount}}</td>
                                                    </tr>
                                                    {% endif %}
                                                {% endif %}
                                            {% endfor %}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-6 col-md-12">
                                <div class="card">
                                    <div class="card-header"><i class="fas fa-chart-bar"></i> Resource Usage</div>
                                    <div class="card-body">
                                        CPU: <span id="cpuStats"></span><br>
                                        <div class="progress">
                                          <div id="cpuUsage" class="progress-bar bg-info" role="progressbar" style="width: 0%;color:black;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                                        </div><br>
                                        Memory: <span id="memoryStats"></span><br>
                                        <div class="progress">
                                          <div id="memoryUsage" class="progress-bar bg-danger" role="progressbar" style="width: 0%;color:black;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                                        </div><br>
                                        Disk: <span id="diskStats"></span><br>
                                        <div class="progress">
                                          <div id="diskUsage" class="progress-bar" role="progressbar" style="width: 0%;color:black;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                                        </div>
                                    </div>
                                </div>
                                <br>
                                <div class="card">
                                    <div class="card-header"><i class="fas fa-chart-bar"></i> Viewer Stats</div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-xl-6 col-md-12">
                                                <div class="callout callout-success"><h4>Current Stream Viewers</h4><br><h2>{{currentViewers}}</h2></div>
                                            </div>
                                            <div class="col-xl-6 col-md-12">
                                                <div class="callout callout-primary"><h4>Total Viewers (30 days)</h4><br><h2>{{viewersTotal}}</h2></div>
                                            </div>
                                        </div>
                                        <div id="statChart">
                                            <canvas id="viewershipChart" width="400" height="400"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br>
                    </div>
                </div>
                <div class="tab-pane fade {% if page == 'settings' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-settings" id="adminSettings">
                    <h5>Configuration Options</h5>
                      <form action="/settings/admin" enctype=multipart/form-data method="post">
                          <div class="row">
                              <div class="col-sm-12 col-md-6">
                                  <h4><i class="fas fa-server"></i> Server Settings</h4>
                                  Server Name: <input type="text" name="serverName" class="form-control" value="{{sysSettings.siteName}}" required autocomplete="new-password">
                                  <br>
                                  <div class="form-row">
                                      <div class="form-group mx-2">
                                        Server Protocol:
                                          <select name="siteProtocol" class="form-control">
                                              <option value="http://" {% if sysSettings.siteProtocol == 'http://' %} selected {% endif %}>http://</option>
                                              <option value="https://" {% if sysSettings.siteProtocol == 'https://' %} selected {% endif %}>https://</option>
                                          </select>
                                      </div>
                                      <div class="form-group mx-2">
                                        Server Hostname/IP Address: <input type="text" name="serverAddress" class="form-control" value="{{sysSettings.siteAddress}}" size="48" required>
                                      </div>
                                  </div>
                                  <div class="form-group">
                                    <label for="maintenanceMode">Maintenance Mode</label><br>
                                    <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="maintenanceMode" name="maintenanceMode" autocomplete="new-password" {% if sysSettings.maintenanceMode == True %} checked {% endif %}>
                                  </div>
                                  <hr>
                                  System Logo:
                                  <img src="{{sysSettings.systemLogo}}" width="32" height="32"><br>
                                  <input type="file" name="photo" class="form-control-file" value="Upload a Logo" style="margin-top:10px;+"><br>
                                  Theme:
                                  <select class="form-control" name="theme">
                                      {% for theme in themeList %}
                                      <option value="{{theme}}" {% if sysSettings.systemTheme == theme %} selected {% endif %}>{{theme}}</option>
                                      {% endfor %}
                                  </select>
                                  <div class="form-group">
                                      <label for="mainPageSort" class="col-form-label">Main Page Sorting</label>
                                      <select class="form-control" id="mainPageSort" name="mainPageSort">
                                          <option value="0" {% if sysSettings.sortMainBy == 0 %} selected {% endif %}>Most Views</option>
                                          <option value="1" {% if sysSettings.sortMainBy == 1 %} selected {% endif %}>Most Recent</option>
                                          <option value="2" {% if sysSettings.sortMainBy == 2 %} selected {% endif %}>Random</option>
                                      </select>
                                  </div>
                                  <hr>
                                  <div class="form-group">
                                    <label for="restreamMaxBitrate" class="col-form-label">Maximum Bitrate for RTMP Restreams (Kb/s)</label><br>
                                    <input type="number" id="restreamMaxBitrate" name="restreamMaxBitrate" class="form-control" value="{{sysSettings.restreamMaxBitrate}}">
                                  </div>
                                  <div class="form-group">
                                    <label for="rangeSlider">Maximum Clip Length</label><br>
                                    <div class="input-group">
                                      <input id="maxClipLength" name="maxClipLength" class="rangeSliderInput form-control" type="range" value="{{sysSettings.maxClipLength}}" style="border:0;" min="0" max="301">
                                      <h3><span id="maxClipLengthLabel" class="rangeSliderValue ml-1 badge badge-large badge-secondary" style="width:100px;">{{sysSettings.maxClipLength|format_clipLength}}</span></h3>
                                      </div>
                                  </div>
                                  <hr>
                                  Allow Users to Record:<br>
                                  <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="recordSelect" name="recordSelect" autocomplete="new-password" {% if sysSettings.allowRecording == True %} checked {% endif %}>
                                  <br>
                                  Allow Users to Upload Video:<br>
                                  <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="uploadSelect" name="uploadSelect" autocomplete="new-password" {% if sysSettings.allowUploads == True %} checked {% endif %}>
                                  <br>
                                  Enable Adaptive Streaming (Can Cause Significant CPU Usage Per Stream)<br>
                                  <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="adaptiveStreaming" name="adaptiveStreaming" autocomplete="new-password" {% if sysSettings.adaptiveStreaming == True %} checked {% endif %}>
                                  <br>
                                  Display Empty Channels, Streamers, and Topics<br>
                                  <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="showEmptyTables" name="showEmptyTables" autocomplete="new-password" {% if sysSettings.showEmptyTables == True %} checked {% endif %}>
                                  <br>
                                  Globally Allow Comments (Can be Disabled on a Per Video Basis)<br>
                                  <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="allowComments" name="allowComments" autocomplete="new-password" {% if sysSettings.allowComments == True %} checked {% endif %}>
                                  <br>
                                  Enable Channel Protection System (Can cause some slowdown with loading images and video)<br>
                                  <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="enableProtection" name="enableProtection" autocomplete="new-password" {% if sysSettings.protectionEnabled == True %} checked {% endif %}>
                              </div>
                              <div class="col-sm-12 col-md-6">
                                  <h4><i class="fas fa-envelope"></i> Email Settings</h4>
                                  <button type="button" class="btn btn-primary my-2" onclick="testEmail();">Test Email Settings</button>
                                  <div id="emailsuccess" style="display:none;"><i class="fas fa-check-circle" style="color:springgreen;"></i> Email Test was Successful!</div>
                                  <div id="emailfailure" style="display:none;"><i class="fas fa-times-circle" style="color:orangered"></i> Email Test Failed!</div>
                                  <br>
                                  SMTP Email From: <input type="email" id="smtpSendAs" name="smtpSendAs" class="form-control" value="{{sysSettings.smtpSendAs}}" required autocomplete="new-password">
                                  SMTP Address: <input type="text" id="smtpAddress" name="smtpAddress" class="form-control" value="{{sysSettings.smtpAddress}}" required autocomplete="new-password">
                                  SMTP Port: <input type="number" id="smtpPort" name="smtpPort" class="form-control" value={{sysSettings.smtpPort}} required autocomplete="new-password">
                                  SMTP Username:<input type="text" id="smtpUser" name="smtpUser" class="form-control" value="{{sysSettings.smtpUsername}}" autocomplete="new-password">
                                  SMTP Password<input type="password" id="smtpPassword" name="smtpPassword" class="form-control" value="{{sysSettings.smtpPassword}}" autocomplete="new-password">
                                  SMTP SSL:<br>
                                  <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="smtpSSL" name="smtpSSL" autocomplete="new-password" {% if sysSettings.smtpSSL == True %} checked {% endif %}>
                                  <br>
                                  SMTP TLS:<br>
                                  <input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="smtpTLS" name="smtpTLS" autocomplete="new-password" {% if sysSettings.smtpTLS == True %} checked {% endif %}>
                                  <hr>
                                  <h4><i class="fas fa-stream"></i> Other</h4>
                                  <div class="form-group">
                                    <label for="serverMessageTitle" class="col-form-label">Server Message Title</label><br>
                                    <input type="text" id="serverMessageTitle" name="serverMessageTitle" class="form-control" value="{{sysSettings.serverMessageTitle}}" size="256">
                                  </div>
                                  <div class="form-group">
                                    <label for="serverMessage" class="col-form-label"><b>Server Message (Displayed on Main Page)</b></label>
                                    <textarea class="form-control" name="serverMessage" id="serverMessage" value="" maxlength="2048">{{sysSettings.serverMessage}}</textarea>
                                  </div>
                              </div>
                              <hr>
                          </div><br>
                          <div class="row">
                              <div class="col-12">
                                  <input type="hidden" value="system" id="settingType" name="settingType">
                                  <div class="form-row text-center">
                                    <button type="submit" class="btn btn-primary btn-block">Submit</button>
                                  </div>
                              </div>
                          </div>
                      </form>
                </div>
                <div class="tab-pane fade {% if page == 'oauth' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-oauth" id="adminOauth">
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    OAuth Provider Listing
                                    <span class="float-right"><button class="btn btn-sm btn-success shadow" type="button" data-toggle="modal" data-target="#newOauthModal"><i class="fas fa-plus"></i></button></span>
                                </div>
                                <div class="card-body">
                                    <table id="oAuthTable" class="table table-borderless" width="100%">
                                        <thead>
                                            <tr>
                                                <th>Provider Name</th>
                                                <th>Authentication Type</th>
                                                <th>Client ID</th>
                                                <th>Authorize URL</th>
                                                <th>Options</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        {% for provider in oAuthProvidersList %}
                                            <tr>
                                                <td>{{provider.name}}</td>
                                                <td>{{provider.preset_auth_type}}</td>
                                                <td>{{provider.client_id}}</td>
                                                <td>{{provider.authorize_url}}</td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-warning shadow edit-oAuth-Button" data-id="{{provider.id}}" data-name="{{provider.name}}" data-friendlyname="{{provider.friendlyName}}"
                                                            data-displaycolor="{{provider.displayColor}}" data-clientid="{{provider.client_id}}" data-clientsecret="{{provider.client_secret}}" data-accesstokenurl="{{provider.access_token_url}}"
                                                            data-accesstokenparams='{{provider.access_token_params|tojson}}' data-authorizeurl="{{provider.authorize_url}}" data-authorizeparams='{{provider.authorize_params|tojson}}'
                                                            data-apibaseurl="{{provider.api_base_url}}" data-clientkwargs='{{provider.client_kwargs|tojson}}' data-profileendpoint="{{provider.profile_endpoint}}" data-usernamevalue="{{provider.username_value}}"
                                                            data-emailvalue="{{provider.email_value}}" data-idvalue="{{provider.id_value}}" data-authtype="{{provider.preset_auth_type}}">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-sm btn-danger shadow" onclick="deleteOAuthProvider('{{provider.id}}');"><i class="far fa-trash-alt"></i></button>
                                                </td>
                                            </tr>
                                        {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal fade" id="newOauthModal" tabindex="-1" role="dialog" aria-labelledby="newOAuthModalTitle" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                        <div class="modal-content">
                          <form action="/settings/admin" id="OAuthForm" method="post">
                          <div class="modal-header">
                            <h5 class="modal-title" id="newOauthModalTitle">Add/Edit an OAuth Provider</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                              <div class="container">
                                <div class="row">
                                    <div class="form-group col-md-12">
                                        <label for="oAuthPreset">Authentication Type</label>
                                        <select class="form-control required" id="oAuthPreset" name="oAuthPreset" required>
                                            <option value="Custom">Custom OAuth2</option>
                                            <option value="Discord">Discord</option>
                                            <option value="Reddit">Reddit</option>
                                            <option value="Facebook">Facebook</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 col-12">
                                        <div id="oAuthNameDiv" class="form-group col-md-12">
                                            <label for="oAuthName">OAuth Provider ID</label>
                                            <input type="text" class="form-control required" id="oAuthName" name="oAuthName" maxlength="40" pattern="^\S+$" required>
                                            <small id="oAuthHelp" class="form-text text-muted">Used for Internal Identification.  No Spaces</small>
                                        </div>
                                        <div id="oAuthFriendlyNameDiv" class="form-group col-md-12">
                                            <label for="oAuthFriendlyName">OAuth Provider Friendly Name</label>
                                            <input type="text" class="form-control required" id="oAuthFriendlyName" name="oAuthFriendlyName" maxlength="64" required>
                                        </div>
                                        <div id="oAuthColorDiv" class="form-group col-md-12">
                                            <label for="oAuthName">Login Button Color</label>
                                            <input type="color" class="form-control required" id="oAuthColor" name="oAuthColor" required>
                                        </div>
                                        <hr>
                                        <div id="oAuthClient_idDiv" class="form-group col-md-12">
                                            <label for="oAuthClient_id">Client ID</label>
                                            <input type="text" class="form-control required" id="oAuthClient_id" name="oAuthClient_id" pattern="^\S+$" required>
                                        </div>
                                        <div id="oAuthClient_secretDiv"  class="form-group col-md-12">
                                            <label for="oAuthClient_secret">Client Secret</label>
                                            <input type="password" class="form-control required" id="oAuthClient_secret" name="oAuthClient_secret" required>
                                        </div>
                                        <div id="oAuthAccess_token_urlDiv" class="form-group col-md-12">
                                            <hr>
                                            <label for="oAuthAccess_token_url">Access Token URL</label>
                                            <input type="text" class="form-control required" id="oAuthAccess_token_url" name="oAuthAccess_token_url" pattern="^\S+$" required>
                                        </div>
                                        <div id="oAuthAccess_token_paramsDiv" class="form-group col-md-12">
                                            <label for="oAuthAccess_token_params">Access Token Params</label>
                                            <textarea id="oAuthAccess_token_params" class="form-control" name="oAuthAccess_token_params"></textarea>
                                        </div>
                                        <div id="oAuthAuthorize_urlDiv" class="form-group col-md-12">
                                            <label for="oAuthAuthorize_url">Authorize URL</label>
                                            <input type="text" class="form-control required" id="oAuthAuthorize_url" name="oAuthAuthorize_url" pattern="^\S+$" required>
                                        </div>
                                        <div id="oAuthAuthorize_paramsDiv" class="form-group col-md-12">
                                            <label for="oAuthAuthorize_params">Authorize Params</label>
                                            <textarea class="form-control" id="oAuthAuthorize_params" name="oAuthAuthorize_params"></textarea>
                                        </div>
                                    </div>
                                    <div class="col-md-6 col-12">
                                        <div id="oAuthApi_base_urlDiv" class="form-group col-md-12">
                                            <label for="oAuthApi_base_url">API Base URL</label>
                                            <input type="text" class="form-control required" id="oAuthApi_base_url" name="oAuthApi_base_url" pattern="^\S+$" required>
                                            <small id="oAuthApi_base_urlHelp" class="form-text text-muted">Full URI for API Requests (including trailing /)</small>
                                        </div>
                                        <div id="oAuthClient_kwargsDiv" class="form-group col-md-12">
                                            <label for="oAuthClient_kwargs">Client Kwargs</label>
                                            <textarea class="form-control" id="oAuthClient_kwargs" name="oAuthClient_kwargs"></textarea>
                                            <small id="oAuthClient_kwargsHelp" class="form-text text-muted">JSON Payload Request - Typically Includes oAuth Client Scope</small>
                                        </div>

                                        <div id="oAuthProfile_endpointDiv" class="form-group col-md-12">
                                            <hr>
                                            <label for="oAuthProfile_endpoint">Profile Endpoint</label>
                                            <input type="text" class="form-control required" id="oAuthProfile_endpoint" name="oAuthProfile_endpoint" required>
                                            <small id="oAuthProfile_endpointHelp" class="form-text text-muted">Relative Path of API Base URL to Retrieve Login User's Profile (no leading /)</small>
                                        </div>
                                        <div id="oAuthIDValueDiv" class="form-group col-md-12">
                                            <label for="oAuthUsername">ID Profile Value</label>
                                            <input type="text" class="form-control required" id="oAuthIDValue" name="oAuthIDValue" required>
                                            <small id="oAuthIDValueHelp" class="form-text text-muted">Unique ID Attribute Retrieved from Profile Endpoint</small>
                                        </div>
                                        <div id="oAuthUsernameDiv" class="form-group col-md-12">
                                            <label for="oAuthUsername">Username Profile Value</label>
                                            <input type="text" class="form-control required" id="oAuthUsername" name="oAuthUsername" required>
                                            <small id="oAuthUsernameHelp" class="form-text text-muted">Username Attribute Retrieved from Profile Endpoint</small>
                                        </div>
                                        <div id="oAuthEmailDiv" class="form-group col-md-12">
                                            <label for="oAuthEmail">Email Profile Value</label>
                                            <input type="text" class="form-control required" id="oAuthEmail" name="oAuthEmail" required>
                                            <small id="oAuthEmailHelp" class="form-text text-muted">Email Address Attribute Retrieved from Profile Endpoint</small>
                                        </div>
                                    </div>
                                    <input type="hidden" id="oAuthID" name="oAuthID">
                                    <input type="hidden" value="oAuthProvider" id="settingType" name="settingType">
                                </div>
                              </div>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="resetOAuthForm();">Cancel</button>
                            <input type="submit" class="btn btn-success" value="Add/Edit">
                          </div>
                          </form>
                        </div>
                      </div>
                    </div>
                    <div class="modal fade" id="deleteOauthModal" tabindex="-1" role="dialog" aria-labelledby="deleteOAuthModalTitle" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                        <div class="modal-content">
                          <form action="/settings/admin" method="post">
                          <div class="modal-header">
                            <h5 class="modal-title" id="deleteOauthModalTitle">Delete a OAuth Provider</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                              <div class="container">
                                <div class="row">
                                    <div class="col-12">
                                        <div class="form-group col-md-12">
                                            <p>Any Users that registered under the OAuth Provider will be reassigned to local authentication and passwords set to a random value.  Users will need to perform a password reset to regain access.</p>
                                            <p>Are you sure you want to delete the OAuth Provider?</p>
                                            <input type="hidden" id="DeleteOAuthProviderID" name="DeleteOAuthProviderID">
                                            <input type="hidden" value="DeleteOAuthProvider" id="settingType" name="settingType">
                                        </div>
                                    </div>
                                </div>
                              </div>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-success" data-dismiss="modal">Cancel</button>
                            <input type="submit" class="btn btn-danger" value="Delete">
                          </div>
                          </form>
                        </div>
                      </div>
                    </div>
                </div>
                <div class="tab-pane fade {% if page == 'ospedge' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-edge" id="edgeSettings">
                    <h5>
                        OSP Edge Streamer Nodes
                    </h5>
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    List of OSP Edge Streamer Nodes
                                    <span class="float-right"><button class="btn btn-sm btn-success shadow" type="button" data-toggle="modal" data-target="#newEdgeModal"><i class="fas fa-plus"></i></button></span><br>
                                    <note style="color:red;">*** A Reload of NGINX is required after any changes for OSP Streaming to work ***</note><br>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="edgeTable" class="table table-borderless" width="100%">
                                            <thead>
                                                <tr>
                                                    <th>Edge Streamer Address</th>
                                                    <th>HTTP Port</th>
                                                    <th>Load %</th>
                                                    <th>Active?</th>
                                                    <th>Status</th>
                                                    <th>Options</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                            {% for node in edgeNodes %}
                                            <tr id="edgeTableRow-{{node.id}}">
                                                <td><a href="/settings/admin/rtmpstat/{% if node.address == sysSettings.siteAddress %}localhost{% else %}{{node.address}}{% endif %}">{{node.address}}</a></td>
                                                <td>{{node.port}}</td>
                                                <td>{{node.loadPct}}</td>
                                                <td><input type="checkbox" data-toggle="toggle" data-width="50" data-on=" " data-off=" " id="activeNode" name="activeSelect" autocomplete="new-password"
                                                           {% if node.active == True %} checked {% endif %} onchange="toggleActiveEdge('{{node.id}}');"></td>
                                                <td id="nodeStatus-{{node.id}}"><span class="badge {% if node.status == 1 or node.address == sysSettings.siteAddress %}badge-success{% elif node.status == 0 %}badge-danger{% endif %}">
                                                    {% if node.status == 1 or node.address == sysSettings.siteAddress %} Online
                                                    {% elif node.status == 0 %} Offline
                                                    {% endif %}
                                                </span>

                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-primary {% if node.address == sysSettings.siteAddress %}disabled{% endif %}" onclick="checkEdge('{{node.id}}')" {% if node.address == sysSettings.siteAddress %}disabled{% endif %}><i class="fas fa-sync-alt"></i></button>
                                                    <button type="button" class="btn btn-sm btn-danger" onclick="deleteEdge('{{node.id}}')"><i class="far fa-trash-alt"></i></button>
                                                </td>
                                            </tr>
                                            {% endfor %}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal fade" id="newEdgeModal" tabindex="-1" role="dialog" aria-labelledby="newEdgeModalTitle" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                        <div class="modal-content">
                          <form action="/settings/admin" method="post">
                          <div class="modal-header">
                            <h5 class="modal-title" id="newEdgeModalTitle">Add a New Edge Streamer Node</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                              <div class="container">
                                <div class="row">
                                    <div class="form-group col-md-6">
                                        <label for="edgeAddress">Full Qualified Domain Name or IP Address:</label>
                                        <input type="text" name="address" id="edgeAddress" class="form-control"
                                               pattern="^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^(?:(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-fA-F]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,1}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,2}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,3}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:[0-9a-fA-F]{1,4})):)(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,4}(?:(?:[0-9a-fA-F]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,5}(?:(?:[0-9a-fA-F]{1,4})))?::)(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,6}(?:(?:[0-9a-fA-F]{1,4})))?::))))$"
                                               required autocomplete="new-password">
                                    </div>
                                    <div class="form-group col-md-3">
                                        <label for="edgeAddress">HTTP Port</label>
                                        <input type="number" name="edgePort" id="edgePort" class="form-control" required autocomplete="new-password" value="80">
                                    </div>
                                    <div class="form-group col-md-3">
                                        <label for="edgeAddress">Load %</label>
                                        <div class="input-group mb-3">
                                            <input type="number" name="edgeLoad" id="edgeLoad" class="form-control" required autocomplete="new-password" min="1" max="100">
                                            <div class="input-group-append">
                                              <span class="input-group-text" id="basic-addon2">%</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <br>
                              </div>
                              <input type="hidden" value="edgeNode" id="settingType" name="settingType">
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                            <input type="submit" class="btn btn-success" value="Add">
                          </div>
                          </form>
                        </div>
                      </div>
                    </div>
                </div>
                <div class="tab-pane fade {% if page == 'webhooks' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-webhooks" id="webhooksSettings">
                <h5>Global Webhooks</h5>
                     <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h6><b><i class="fas fa-globe"></i> Active Webhooks</b>
                                        <span class="float-right"><button class="btn btn-sm btn-success shadow" type="button" onclick="openNewWebhookModal();"><i class="fas fa-plus"></i></button></span>
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div id="webhookList">
                                        <div class="table-responsive">
                                            <table id="webhookTable" class="table table-borderless" width="100%">
                                                <thead>
                                                    <tr>
                                                        <th>Webhook Name</th>
                                                        <th>Trigger</th>
                                                        <th></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    {% for webhook in globalHooks %}
                                                    <tr id="webhookTableRow-{{webhook.id}}">
                                                        <td id="webhookRowName-{{webhook.id}}">{{webhook.name}}</td>
                                                        <td id="webhookRowEndpoint-{{webhook.id}}" style="display:none;">{{webhook.endpointURL}}</td>
                                                        <td id="webhookRowTrigger-{{webhook.id}}">{{webhook.requestTrigger|get_webhookTrigger}}</td>
                                                        <td id="webhookRowType-{{webhook.id}}" style="display:none;">{{webhook.requestType}}</td>
                                                        <td id="webhookRowHeader-{{webhook.id}}" style="display:none;">{{webhook.requestHeader}}</td>
                                                        <td id="webhookRowPayload-{{webhook.id}}" style="display:none;">{{webhook.requestPayload}}</td>
                                                        <td>
                                                            <button type="button" class="btn btn-sm btn-warning" onclick="editWebhook('{{webhook.id}}')"><i class="fas fa-edit"></i></button>
                                                            <button type="button" class="btn btn-sm btn-success" onclick="testWebhook('{{webhook.id}}')"><i class="fas fa-vial"></i></button>
                                                            <button type="button" class="btn btn-sm btn-danger" onclick="deleteWebhookModal('{{webhook.id}}')"><i class="far fa-trash-alt"></i></button>
                                                        </td>
                                                    </tr>
                                                    {% endfor %}
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                     </div>
                     <div class="modal fade" id="confirmDeleteWebhookModal" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteWebhookModalTitle" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h5 class="modal-title" id="confirmDeleteWebhookModalTitle">Delete Webhook</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                              Are you sure you want to delete the webhook?
                              <input id="deleteWebhookID" type="hidden">
                          </div>
                          <div class="modal-footer">
                              <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                              <button type="button" class="btn btn-success" data-dismiss="modal" onclick="deleteWebhook();">Delete</button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="modal fade" id="newWebhookModal" tabindex="-1" role="dialog" aria-labelledby="newWebhookModalTitle" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h5 class="modal-title" id="newWebhookModalTitle">Create/Edit Webhook</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                             <div class="row">
                                 <div class="col-12">
                                     <div class="form-row">
                                        <div class="form-group col-md-4">
                                            <label for="webhookName">Name</label>
                                            <input id="webhookName" class="form-control" autocomplete="new-password">
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="webhookEndpoint">Endpoint URL</label>
                                            <input id="webhookEndpoint" class="form-control" autocomplete="new-password">
                                        </div>
                                        <div class="col-md-4"></div>
                                        <div class="form-group col-md-12">
                                            <label for="webhookHeader">Request Header</label>
                                            <textarea id="webhookHeader" class="form-control" maxlength="4096"></textarea>
                                        </div>
                                        <div class="form-group col-md-12">
                                            <label for="webhookPayload">Payload</label>
                                            <textarea id="webhookPayload" class="form-control" cols=50 rows=25 maxlength="4096"></textarea>
                                        </div>
                                        <div class="form-group col-md-2">
                                            <label for="webhookReqType">Type</label>
                                            <select id="webhookReqType" class="form-control">
                                                 <option value=0 selected>POST</option>
                                                 <option value=1>GET</option>
                                                 <option value=2>PUT</option>
                                                 <option value=3>DELETE</option>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-3">
                                            <label for="webhookTrigger">Trigger Event</label>
                                            <select id="webhookTrigger" class="form-control">
                                                 <option value=0 selected>Stream Start</option>
                                                 <option value=1>Stream End</option>
                                                 <option value=2>Stream Viewer Join</option>
                                                 <option value=4>Stream Name Change</option>
                                                 <option value=5>Chat Message</option>
                                                 <option value=6>New Video</option>
                                                 <option value=7>Video Comment</option>
                                                 <option value=9>Video Name Change</option>
                                                 <option value=10>Channel Subscription</option>
                                                 <option value=20>New User</option>
                                            </select>
                                        </div>
                                        <input id="webhookInputAction" type="hidden">
                                        <input id="webhookID" type="hidden">
                                     </div>
                                 </div>
                             </div>
                          </div>
                          <div class="modal-footer">
                              <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                              <button type="button" class="btn btn-success" data-dismiss="modal" onclick="submitWebhook();">Save</button>
                          </div>
                        </div>
                      </div>
                    </div>
                </div>
                <div class="tab-pane fade {% if page == 'users' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-users" id="userList">
                    <h5>User List <button class="btn btn-primary" data-toggle="modal" data-target="#newUserModal"><i class="fas fa-plus-square"></i> New User</button></h5>
                    <div class="container-fluid justify-content-center" style="width:100%;padding-top:15px;">
                        <div class="input-group">
                            <div class="input-group-prepend shadow">
                                <div class="input-group-text"><i class="fas fa-search"></i></div>
                            </div>
                            <input type="text" id="search" name="search" class="searchBar form-control shadow" placeholder="Search">
                        </div>
                    </div>
                    <br>
                    <div class="container-fluid">

                    {% for user in userList %}
                        <div class="row">
                            <div class="col-12">
                                <div class="card shadow searchable">
                                    <div class="card-header {% if user.active == true %} bg-success{% endif %}">
                                        <b><a href="/streamers/{{user.id}}/" class="text-dark">{{user.username}}</a></b>
                                        <div class="float-right">
                                            <a href="/settings/admin?action=toggleActive&setting=users&userID={{user.id}}" class="btn btn-sm {% if user.id == current_user.id %} disabled {% endif %} {% if user.active == True %}btn-secondary {% else %} btn-success {% endif %} shadow"><i class="fas {% if user.active == True %}fa-user-slash{% else %}fa-user{% endif %}"></i></a>
                                            <a href="/settings/admin?action=delete&setting=users&userID={{user.id}}" class="btn btn-sm btn-danger shadow {% if user.id == current_user.id %} disabled {% endif %}"><i class="far fa-trash-alt"></i></a>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                          <div class="col-xl-1 col-sm-12">
                                            <img src="/images/{{user.pictureLocation}}" width="64px" height="64px" onerror="this.src='/static/img/user2.png';">
                                          </div>
                                          <div class="col-xl-2 col-sm-12">
                                            <i class="fas fa-at"></i> {{user.email}}<br>
                                            <i class="fas fa-passport"></i> <span class="badge badge-primary">{% if user.authType == 0 %}Local{% elif user.authType == 1 %}oAuth{% endif %}</span><br>
                                            {% if user.authType == 1 %}<i class="fas fa-file-contract"></i> {{user.oAuthProvider}} {% endif %}
                                          </div>
                                          <div class="col-xl-3 col-sm-12">
                                            <i class="fas fa-key"></i> Roles: <button type="button" class="btn btn-sm btn-warning dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Add Role</button>
                                          <div class="dropdown-menu">
                                            <a class="dropdown-item" href="/settings/admin?action=add&setting=userRole&userID={{user.id}}&roleName=Admin">Admin</a>
                                            <a class="dropdown-item" href="/settings/admin?action=add&setting=userRole&userID={{user.id}}&roleName=Streamer">Streamer</a>
                                              {% if user.has_role('Streamer') %}
                                                <a class="dropdown-item" href="/settings/admin?action=add&setting=userRole&userID={{user.id}}&roleName=Recorder">Recorder</a>
                                                <a class="dropdown-item" href="/settings/admin?action=add&setting=userRole&userID={{user.id}}&roleName=Uploader">Uploader</a>
                                              {% endif %}
                                            <a class="dropdown-item" href="/settings/admin?action=add&setting=userRole&userID={{user.id}}&roleName=User">User</a>
                                            </div><br>
                                            {% for role in user.roles %}
                                            <span class="badge badge-info">{{role.name}} <a href="/settings/admin?action=delete&setting=userRole&userID={{user.id}}&roleID={{role.id}}"><i class="far fa-trash-alt"></i></a></span><br>
                                          {% endfor %}
                                          </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br>
                    {% endfor %}
                    </div>
                        <div class="modal fade" id="newUserModal" tabindex="-1" role="dialog" aria-labelledby="newUserModalTitle" aria-hidden="true">
                          <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                            <div class="modal-content">
                              <form action="/settings/admin" method="post" onsubmit="return passwordCheck()">
                              <div class="modal-header">
                                <h5 class="modal-title" id="newUserModalTitle">Create New User</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                              </div>
                              <div class="modal-body">
                                  <div class="container">
                                    <div class="row">
                                        <div class="col-12">
                                            <label for="username">Username</label>
                                            <input type="text" name="username" id="username" class="form-control" required autocomplete="new-password">
                                        </div>
                                    </div>
                                    <br>
                                    <div class="row">
                                        <div class="col-12">
                                            <label for="emailaddress">Email Address</label>
                                            <input type="text" name="emailaddress" id="emailaddress" class="form-control" required autocomplete="new-password">
                                        </div>
                                    </div>
                                    <br>
                                    <div class="row">
                                        <div class="col-12">
                                            <label for="password1">Password</label>
                                            <input type="password" name="password1" id="password1" class="form-control" required autocomplete="new-password">
                                        </div>
                                        <br>
                                        <div class="col-12">
                                            <label for="password2">Confirm Password</label>
                                            <input type="password" name="password2" id="password2" class="form-control" required autocomplete="new-password">
                                        </div>
                                    </div>
                                    <br>

                                  </div>
                                  <input type="hidden" value="newuser" id="settingType" name="settingType">
                              </div>
                              <div class="modal-footer">
                                <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                                <input type="submit" class="btn btn-success" value="Create">
                              </div>
                              </form>
                            </div>
                          </div>
                        </div>
                    </div>
                <div class="tab-pane fade {% if page == 'topics' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-topics" id="topicsList">
                    <h5>Topics List <div class="float-right"></div><button class="btn btn-primary" data-toggle="modal" data-target="#newTopicModal"><i class="fas fa-plus-square"></i> New Topic</button></h5></h5>
                    <div class="container-fluid">
                        {% for topic in topicsList %}
                        <div class="row">
                            <div class="col-12">
                                <form action="/settings/admin" enctype=multipart/form-data method="post">
                                <div class="card shadow">
                                  <div class="card-header">
                                    <div class="row">
                                      <div class="col-4">
                                        <input type="text" name="name" id="name" class="form-control" value="{{topic.name}}" required autocomplete="new-password">
                                      </div>
                                      <div class="col-8">
                                          <div class="float-right">
                                            <button type="submit" class="btn btn-success shadow"><i class="fas fa-edit"></i></button>
                                            <a href="/settings/admin?action=delete&setting=topics&topicID={{topic.id}}" class="btn btn-danger shadow"><i class="far fa-trash-alt"></i></a>
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  <div class="card-body">
                                    <img width="284px" height="155px" src="/images/{{topic.iconClass}}" onerror="this.src='/static/img/video-placeholder.jpg';">
                                    <br><br>
                                    <div class="custom-file">
                                      <input type="file" class="custom-file-input" name=photo id="photo" autocomplete="new-password">
                                      <label class="custom-file-label" for="photo">Upload a Photo</label>
                                    </div>
                                    <input type="hidden" value="{{topic.id}}" id="topicID" name="topicID">
                                    <input type="hidden" value="topics" id="settingType" name="settingType">
                                  </div>
                                </div>
                                </form>
                                <br>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    <div class="modal fade" id="newTopicModal" tabindex="-1" role="dialog" aria-labelledby="newTopicModalTitle" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                        <div class="modal-content">
                          <form action="/settings/admin" enctype=multipart/form-data method="post">
                          <div class="modal-header">
                            <h5 class="modal-title" id="newTopicModalTitle">Create New Topic</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                              <div class="container">
                                <div class="row">
                                    <div class="col-12">
                                        <input type="text" name="name" id="name" class="form-control" required autocomplete="new-password">
                                    </div>
                                </div>
                                <br>
                                <div class="row">
                                      <div class="col-12">
                                        <img width="284" height="155" src="/static/img/video-placeholder.jpg">
                                      </div>
                                </div>
                                <br>
                                <div class="row">
                                      <div class="col-12">
                                          <div class="custom-file">
                                            <input type="file" class="custom-file-input" name=photo id="photo">
                                            <label class="custom-file-label" for="photo">Upload a Photo</label>
                                          </div>
                                      </div>
                                </div>
                              </div>
                              <input type="hidden" value="topics" id="settingType" name="settingType">
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                            <input type="submit" class="btn btn-success" value="Create">
                          </div>
                          </form>
                        </div>
                      </div>
                    </div>
                </div>
                <div class="tab-pane fade {% if page == 'channels' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-channels" id="channelsList">
                    <h5>Channels List</h5>
                    <div class="container-fluid justify-content-center" style="width:100%;padding-top:15px;">
                        <div class="input-group">
                            <div class="input-group-prepend shadow">
                                <div class="input-group-text"><i class="fas fa-search"></i></div>
                            </div>
                            <input type="text" id="search" name="search" class="searchBar form-control shadow" placeholder="Search">
                        </div>
                    </div>
                    <br>
                    <div class="container-fluid">
                        {% for channel in channelList %}
                        <div id="channelCardRow-{{channel.id}}" class="row">
                            <div class="col-12">
                                <div class="card shadow searchable">
                                  <div class="card-header">
                                      <b><span class="video-title"><a href="/channel/{{channel.id}}/">{{channel.channelName}}</a></span></b>
                                    <div class="float-right"><button class="btn btn-sm btn-danger" type="button" onclick="deleteChannelModal('{{channel.id}}')"><i class="far fa-trash-alt"></i></button></div>
                                  </div>
                                  <div class="card-body">
                                    <div class="row">
                                      <div class="col-md-3 col-12 displayCard"><img class="channel-img" src="/images/{{channel.imageLocation}}" onerror="this.src='/static/img/video-placeholder.jpg';"></div>
                                      <div class="col-md-3 col-12">
                                        <i class="fas fa-hashtag"></i> {{channel.topic|get_topicName}} <br>
                                        <i class="fas fa-user"></i> {{channel.owningUser|get_userName}} <br>
                                        <i class="fas fa-terminal"></i> {{channel.channelLoc}} <br>
                                        <i class="fas fa-eye"></i> {{channel.views}} <br>
                                        <i class="fas fa-hdd"></i> {{channel.channelLoc|get_diskUsage}} <br>
                                      </div>
                                      <div class="col-md-4 col-12">
                                        <i class="fas fa-paragraph"></i> {{channel.description}}<br>
                                      </div>
                                      <div class="col-md-2 col-12">
                                        <i class="fas fa-comment"></i> <span class="badge {% if channel.chatEnabled == True %} badge-success {% elif channel.chatEnabled == False %} badge-danger {% endif %}"> {{channel.chatEnabled}} </span> <br>
                                        <i class="fas fa-save"></i> <span class="badge {% if channel.record == True %} badge-success {% elif channel.record == False %} badge-danger {% endif %}"> {{channel.record}}</span> <br>
                                        <i class="fas fa-comments"></i> <span class="badge {% if channel.allowComments == True %} badge-success {% elif channel.allowComments == False %} badge-danger {% endif %}"> {{channel.allowComments}}</span> <br>
                                        <i class="fas fa-lock"></i> <span class="badge {% if channel.protected == True %} badge-success {% elif channel.protected == False %} badge-danger {% endif %}"> {{channel.protected}}</span><br>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                            </div>
                        </div>
                        <br>
                        {% endfor %}
                    </div>
                    <div class="modal fade" id="confirmDeleteChannelModal" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteChannelModalTitle" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                        <div class="modal-content">
                          <form action="/settings/admin" method="post">
                          <div class="modal-header">
                            <h5 class="modal-title" id="confirmDeleteChannelModalTitle">Delete Channel</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                              Deleting a channel will remove all associated videos and clip.  Are you sure you want to delete the channel?<br>
                              <input type="hidden" id="deleteChannelID" name="channelID">
                          </div>
                          <div class="modal-footer">
                              <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                              <button type="button" class="btn btn-danger" onclick="deleteChannel();" data-dismiss="modal">Delete</button>
                          </div>
                          </form>
                        </div>
                      </div>
                    </div>
                </div>
                <div class="tab-pane fade {% if page == 'streams' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-streams" id="streamsList">
                    <h5>Stream List</h5>
                    <div class="container-fluid justify-content-center" style="width:100%;padding-top:15px;">
                        <div class="input-group">
                            <div class="input-group-prepend shadow">
                                <div class="input-group-text"><i class="fas fa-search"></i></div>
                            </div>
                            <input type="text" id="search" name="search" class="searchBar form-control shadow" placeholder="Search">
                        </div>
                    </div>
                    <br>
                    <div class="container-fluid">
                        {% for stream in streamList %}
                        <div id="streamCard-{{stream.id}}" class="row">
                            <div class="col-12">
                                <div class="card shadow searchable">
                                  <div class="card-header">
                                      <span class="video-title"><a href="/view/{{stream.channel.channelLoc}}/"><b>{{stream.streamName}}</b></a></span>
                                      <div class="float-right"><button type="button" class="btn btn-sm btn-danger" onclick="openStreamDeleteModal('{{stream.id}}')"><i class="fas fa-trash-alt"></i></button></div>
                                  </div>
                                  <div class="card-body">
                                    <div class="row">
                                      <div class="col-xl-3 col-sm-12">
                                        <img width="100%" src="/stream-thumb/{{stream.channel.channelLoc}}.png" onerror="this.src='/static/img/video-placeholder.jpg';"><br>
                                      </div>
                                      <div class="col-xl-3 col-sm-12">
                                        <i class="fas fa-video"></i> {{stream.channel.channelName}} <br>
                                        <i class="fas fa-user"></i> {{stream.channel.owningUser|get_userName}} <br>
                                        <i class="fas fa-hashtag"></i> {{stream.channel.topic|get_topicName}} <br>
                                        <i class="fas fa-eye"></i> {{stream.currentViewers}} <br>
                                        <i class="fas fa-users"></i> {{stream.totalViewers}} <br>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    <div class="modal fade" id="deleteStreamModal" tabindex="-1" role="dialog" aria-labelledby="deleteStreamModalTitle" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                        <div class="modal-content">
                          <form action="/settings/admin" method="post">
                          <div class="modal-header">
                            <h5 class="modal-title" id="deleteStreamModalTitle">Delete Active Stream</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                              Deleting a stream will remove the entry from showing on any video listing.  Are you sure you want to delete the stream?<br>
                              <input type="hidden" id="deleteStreamID" name="streamID">
                          </div>
                          <div class="modal-footer">
                              <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                              <button type="button" class="btn btn-danger" onclick="deleteStream()" data-dismiss="modal">Delete</button>
                          </div>
                          </form>
                        </div>
                      </div>
                    </div>
                </div>
                <div class="tab-pane fade {% if page == 'logs' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-logs" id="logs">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-lg-10 col-md-12">
                                <h5>Logs</h5>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <table class="table table-hover" id="logTable">
                                    <thead class="thead-light">
                                    <tr>
                                        <th>
                                            <b>Timestamp</b>
                                        </th>
                                        <th>
                                            <b>Type</b>
                                        </th>
                                        <th>
                                            <b>Message</b>
                                        </th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {% for log in logsList %}
                                        <tr>
                                            <td>
                                                {{log.timestamp|normalize_date}}
                                            </td>
                                            <td>
                                                {{log.type|get_logType}}
                                            </td>
                                            <td>
                                                {{log.message}}
                                            </td>
                                        </tr>
                                    {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="tab-pane fade {% if page == 'backup' %}show active{% endif %}" role="tabpanel" aria-labelledby="admin-content-backuprestore" id="backuprestore">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-lg-6 col-md-12">
                                <h4>Backup the OSP Database</h4>
                                <a href="/settings/admin?action=backup" class="btn btn-primary">Download</a>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-lg-6 col-md-12">
                                <h4>Restore the OSP Database</h4>
                                <p>** Restoring a backup will wipe all existing data! **</p>
                                <form action="/settings/dbRestore" enctype=multipart/form-data method="post">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" name=restoreData id="restoreData" required>
                                        <label class="custom-file-label" for="restoreData">Upload Backup File</label>
                                        <script>
                                            $('#restoreData').on('change',function(){
                                                //get the file name
                                                var fileName = $(this).val();
                                                //replace the "Choose a file" label
                                                $(this).next('.custom-file-label').html(fileName);
                                            })
                                        </script>
                                    </div>
                                    <br><br>
                                    <h5>Restore Options</h5>
                                    <div class="form-check">
                                      <input class="form-check-input" type="checkbox" value="" name="restoreVideos" id="restoreVideos">
                                      <label class="form-check-label" for="restoreVideos">
                                        Restore Recorded Video DB Table
                                      </label>
                                    </div>
                                    <br>
                                    <input type="hidden" value="dbRestore" id="settingType" name="settingType">
                                    <input type="submit" class="btn btn-warning" value="Restore">
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script type="text/javascript" src="/static/vendor/datatables/js/datatables.js"></script>
<script>
    $(document).ready(function() {
        $('#logTable').DataTable({
            "order": [[ 0, "desc" ]]
        });
    } );
</script>

<script>
    function toggleDiv(selDiv){
        var divid = '#' + selDiv;
        $('.settingsOption').hide();
        $(divid).show();
    }
</script>

<script>
    function deleteOAuthProvider(providerID) {
        document.getElementById('DeleteOAuthProviderID').value = providerID;
        $('#deleteOauthModal').modal('show');
    }

    function updateOAuthModalWindowLayout() {
        var authType = document.getElementById("oAuthPreset").value;
        switch(authType) {
            case "Custom":
                $("#oAuthAccess_token_url").attr("disabled", false);
                $("#oAuthAccess_token_urlDiv").show();
                $("#oAuthAccess_token_params").attr("disabled", false);
                $("#oAuthAccess_token_paramsDiv").show();
                $("#oAuthAuthorize_url").attr("disabled", false);
                $("#oAuthAuthorize_urlDiv").show();
                $("#oAuthAuthorize_params").attr("disabled", false);
                $("#oAuthAuthorize_paramsDiv").show();
                $("#oAuthApi_base_url").attr("disabled", false);
                $("#oAuthApi_base_urlDiv").show();
                $("#oAuthClient_kwargs").attr("disabled", false);
                $("#oAuthClient_kwargsDiv").show();
                $("#oAuthProfile_endpoint").attr("disabled", false);
                $("#oAuthProfile_endpointDiv").show();
                $("#oAuthIDValue").attr("disabled", false);
                $("#oAuthIDValueDiv").show();
                $("#oAuthUsername").attr("disabled", false);
                $("#oAuthUsernameDiv").show();
                $("#oAuthEmail").attr("disabled", false);
                $("#oAuthEmailDiv").show();
                break;
            default:
                $("#oAuthAccess_token_url").attr("disabled", true);
                $("#oAuthAccess_token_urlDiv").hide();
                $("#oAuthAccess_token_params").attr("disabled", true);
                $("#oAuthAccess_token_paramsDiv").hide();
                $("#oAuthAuthorize_url").attr("disabled", true);
                $("#oAuthAuthorize_urlDiv").hide();
                $("#oAuthAuthorize_params").attr("disabled", true);
                $("#oAuthAuthorize_paramsDiv").hide();
                $("#oAuthApi_base_url").attr("disabled", true);
                $("#oAuthApi_base_urlDiv").hide();
                $("#oAuthClient_kwargs").attr("disabled", true);
                $("#oAuthClient_kwargsDiv").hide();
                $("#oAuthProfile_endpoint").attr("disabled", true);
                $("#oAuthProfile_endpointDiv").hide();
                $("#oAuthIDValue").attr("disabled", true);
                $("#oAuthIDValueDiv").hide();
                $("#oAuthUsername").attr("disabled", true);
                $("#oAuthUsernameDiv").hide();
                $("#oAuthEmail").attr("disabled", true);
                $("#oAuthEmailDiv").hide();
                break;
        }
    }

    $(document).on("click", ".edit-oAuth-Button", function () {

         var oAuthID = $(this).data('id');
         var oAuthName = $(this).data('name');
         var oAuthType = $(this).data('authtype');
         var oAuthFriendlyName = $(this).data('friendlyname');
         var oAuthDisplayColor = $(this).data('displaycolor');
         var oAuthClientID = $(this).data('clientid');
         var oAuthClientSecret = $(this).data('clientsecret');
         var oAuthAccessTokenURL = $(this).data('accesstokenurl');
         var oAuthAccessTokenParams = $(this).data('accesstokenparams');
         var oAuthAuthorizeURL = $(this).data('authorizeurl');
         var oAuthAuthorizeParams = $(this).data('authorizeparams');
         var oAuthAPIBaseURL = $(this).data('apibaseurl');
         var oAuthClientKwargs = $(this).data('clientkwargs');
         var oAuthProfileEndpoint = $(this).data('profileendpoint');
         var oAuthIDValue= $(this).data('idvalue');
         var oAuthUsername = $(this).data('usernamevalue');
         var oAuthEmail = $(this).data('emailvalue');
         $("#oAuthID").val( oAuthID );
         $("#oAuthPreset").val( oAuthType )
         $("#oAuthName").val( oAuthName );
         $("#oAuthFriendlyName").val( oAuthFriendlyName );
         $("#oAuthColor").val( oAuthDisplayColor );
         $("#oAuthClient_id").val( oAuthClientID );
         $("#oAuthClient_secret").val( oAuthClientSecret );
         $("#oAuthAccess_token_url").val( oAuthAccessTokenURL );
         if (oAuthAccessTokenParams != 'None') {
             $("#oAuthAccess_token_params").val(JSON.parse(oAuthAccessTokenParams));
         }
         $("#oAuthAuthorize_url").val( oAuthAuthorizeURL );
         if (oAuthAuthorizeParams != 'None') {
             $("#oAuthAuthorize_params").val(JSON.parse(oAuthAuthorizeParams));
         }
         $("#oAuthApi_base_url").val( oAuthAPIBaseURL );
         if (oAuthClientKwargs != 'None') {
             $("#oAuthClient_kwargs").val(JSON.parse(oAuthClientKwargs));
         }
         $("#oAuthProfile_endpoint").val( oAuthProfileEndpoint );
         $("#oAuthIDValue").val( oAuthIDValue );
         $("#oAuthUsername").val( oAuthUsername );
         $("#oAuthEmail").val( oAuthEmail );
         updateOAuthModalWindowLayout();
         $("#newOauthModal").modal('show');
    });

    // Set Presets for oAuth
    $(document).on("change", "#oAuthPreset", function () {
        updateOAuthModalWindowLayout();
    });

    function resetOAuthForm() {
        document.getElementById("OAuthForm").reset();
        $("#oAuthID").val('');
        updateOAuthModalWindowLayout();
    }
</script>

<script type="text/javascript" charset="utf-8">
    var conn_options = {
        'sync disconnect on unload':true
    };

    var socket = io();
</script>

<script>
    socket.on('connect', function() {
        socket.emit('getServerResources',{data:"0"});
        console.log('Sent Resource Request')
    });
</script>

<script>
    setInterval(function() {
      socket.emit('getServerResources',{data:"0"});
      console.log('Sent Resource Request')
    },10000 );
</script>

<script>
    socket.on('serverResources', function(msg) {

        $('#cpuUsage').attr('aria-valuenow', msg['cpuUsage']).css('width',msg['cpuUsage'] + '%');
        $('#cpuUsage').text(msg['cpuUsage'] + '%');
        $('#cpuStats').text(msg['cpuLoad']);

        $('#memoryUsage').attr('aria-valuenow', msg['memoryUsage']).css('width',msg['memoryUsage'] + '%');
        $('#memoryUsage').text(msg['memoryUsage'] + '%');
        $('#memoryStats').text(msg['memoryUsageAvailable'] + ' MB / ' + msg['memoryUsageTotal'] + ' MB');

        $('#diskUsage').attr('aria-valuenow', msg['diskUsage']).css('width',msg['diskUsage'] + '%');
        $('#diskUsage').text(msg['diskUsage'] + '%');
        $('#diskStats').text(msg['diskFree'] + ' MB / ' + msg['diskTotal'] + ' MB');

    });
</script>

<script>
    socket.on('testEmailResults', function(msg) {
        var results = msg['results'];
        if (results == "True") {
            document.getElementById("emailsuccess").style.display = "Block";
        } else if (results == "False") {
            document.getElementById("emailfailure").style.display = "Block";
        }
    });
</script>

<script>
    function testEmail(){
        smtpAddress = document.getElementById("smtpAddress").value;
        smtpPort = document.getElementById("smtpPort").value;
        smtpTLS = document.getElementById("smtpTLS").checked;
        smtpSSL = document.getElementById("smtpSSL").checked;
        smtpUser = document.getElementById("smtpUser").value;
        smtpPassword = document.getElementById("smtpPassword").value;
        smtpSender = document.getElementById("smtpSendAs").value;

        document.getElementById("emailsuccess").style.display = "None";
        document.getElementById("emailfailure").style.display = "None";

        socket.emit('testEmail', {smtpServer:smtpAddress, smtpPort:smtpPort, smtpTLS: smtpTLS, smtpSSL:smtpSSL, smtpUsername:smtpUser, smtpPassword:smtpPassword, smtpSender:smtpSender, smtpReceiver:smtpSender});
    }
</script>

<script>
    var ctx = document.getElementById('viewershipChart').getContext('2d');
    ctx.canvas.width = 1024
    ctx.canvas.height = 380;
    var chart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'bar',

        // The data for our dataset
        data: {

            datasets: [{
                label: "Live Viewers",
                fill: true,
                borderColor: 'rgb(40, 90, 150)',
                backgroundColor: 'rgb(40, 90, 150)',
                spanGaps: true,
                lineTension: 0,
                data:[
                    {% for entry in statsViewsDay['live'] %}
                        {x:'{{entry['t']}}',y:{{entry['y']}}},
                    {% endfor %}
                ]},
                {
                label: "Video Viewers",
                fill: true,
                borderColor: 'rgb(90, 150, 40)',
                backgroundColor: 'rgb(90, 150, 40)',
                spanGaps: true,
                lineTension: 0,
                data:[
                    {% for entry in statsViewsDay['recorded'] %}
                        {x:'{{entry['t']}}', y:{{entry['y']}}},
                    {% endfor %}
                ]
            }]
        },

        // Configuration options go here
        options: {
            scales: {
                xAxes: [{
                    type: 'time',
                    time: {
                        parser: 'YYYY-MM-DD',
                        unit: 'day'
                    }
                }],
            }
        }
    });
</script>

<script>
    function deleteEdge(edgeID) {
        socket.emit('deleteOSPEdge', {edgeID: edgeID});
        var edgeTableRow = document.getElementById('edgeTableRow-' + edgeID);
        edgeTableRow.parentNode.removeChild(edgeTableRow);
    }

    function toggleActiveEdge(edgeID) {
        socket.emit('toggleOSPEdge', {edgeID: edgeID});
    }

    function checkEdge(edgeID) {
        var oldStatusDiv = document.getElementById('nodeStatus-' + edgeID);
        oldStatusDiv.innerHTML = '<span id="nodeStatus-' + edgeID + '"><div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div></span>';
        socket.emit('checkEdge', {edgeID: edgeID});
    }


    socket.on('edgeNodeCheckResults', function (msg) {
        var edgeID = msg['edgeID'];
        var edgeStatus = Number(msg['status']);
        var nodeStatusDiv = document.getElementById('nodeStatus-' + edgeID);

        var newSpan;

        if (edgeStatus == 0) {
            newSpan = '<span class="badge badge-danger">Offline</span>';
        } else if (edgeStatus == 1) {
            newSpan = '<span class="badge badge-success">Online</span>';
        }

        nodeStatusDiv.innerHTML = newSpan;
    });

</script>

<script>
    function deleteWebhookModal(webhookID) {
        document.getElementById('deleteWebhookID').value = webhookID;
        $('#confirmDeleteWebhookModal').modal('show');
    }

    function deleteWebhook() {
        var webhookID = document.getElementById('deleteWebhookID').value;
        socket.emit('deleteGlobalWebhook', {webhookID: webhookID});
        var webhookTableRow = document.getElementById('webhookTableRow-' + webhookID);
        webhookTableRow.parentNode.removeChild(webhookTableRow);
    }

    function testWebhook(webhookID) {
        socket.emit('testWebhook', {webhookID: webhookID, webhookType: 'global'});
        createNewBSAlert("Webhook Test Sent","success")
    }

    function deleteChannelModal(channelID) {
        document.getElementById('deleteChannelID').value = channelID;
        $('#confirmDeleteChannelModal').modal('show');
    }

    function deleteChannel() {
        var channelID = document.getElementById('deleteChannelID').value;
        socket.emit('deleteChannel', {channelID: channelID});
        var channelTableRow = document.getElementById('channelCardRow-' + channelID);
        channelTableRow.parentNode.removeChild(channelTableRow);
    }
</script>

<script>
    function openNewWebhookModal() {
        $('#newWebhookModal').modal('show');
        var webhookName = document.getElementById('webhookName');
        var webhookEndpoint = document.getElementById('webhookEndpoint');
        var webhookHeader = document.getElementById('webhookHeader');
        var webhookPayload = document.getElementById('webhookPayload');
        var webhookReqTypeElement = (document.getElementById('webhookReqType'));
        var webhookTriggerElement = document.getElementById('webhookTrigger');
        var webhookInputAction = document.getElementById('webhookInputAction');
        var webhookInputID = document.getElementById('webhookID');

        webhookInputID.value = 'New';
        webhookName.value = "";
        webhookEndpoint.value = "";
        webhookHeader.value = "";
        webhookPayload.value = "";
        webhookReqTypeElement.value = 0;
        webhookTriggerElement.value = 0;
        webhookInputAction.value = 'new';
    }
</script>

<script>
	function submitWebhook() {
        var webhookName = document.getElementById('webhookName').value;
        var webhookEndpoint = document.getElementById('webhookEndpoint').value;
        var webhookHeader = document.getElementById('webhookHeader').value;
        var webhookPayload = document.getElementById('webhookPayload').value;
        var webhookReqTypeElement = (document.getElementById('webhookReqType'));
        var webhookTriggerElement = document.getElementById('webhookTrigger');
        var webhookReqType = webhookReqTypeElement.options[webhookReqTypeElement.selectedIndex].value;
        var webhookTrigger = webhookTriggerElement.options[webhookTriggerElement.selectedIndex].value;
        var webhookInputAction = document.getElementById('webhookInputAction').value;
        var webhookInputID = document.getElementById('webhookID').value;

        if (webhookName == '') {
            (document.getElementById('webhookName')).setCustomValidity('Name is Required');
        }
        if (webhookEndpoint == '') {
            (document.getElementById('webhookEndpoint')).setCustomValidity('Endpoint URL is Required');
        }
        socket.emit('submitGlobalWebhook', {webhookName: webhookName, webhookEndpoint: webhookEndpoint, webhookHeader:webhookHeader, webhookPayload:webhookPayload, webhookReqType: webhookReqType, webhookTrigger: webhookTrigger, inputAction:webhookInputAction, webhookInputID:webhookInputID});
	}
</script>

<script>
    function editWebhook(webhookID) {
        var webhookTrigger = document.getElementById('webhookTrigger');
        var webhookName = document.getElementById('webhookName');
        var webhookEndpoint = document.getElementById('webhookEndpoint');
        var webhookHeader = document.getElementById('webhookHeader');
        var webhookPayload = document.getElementById('webhookPayload');
        var webhookReqTypeElement = document.getElementById('webhookReqType');
        var webhookInputAction = document.getElementById('webhookInputAction');
        var webhookInputID = document.getElementById('webhookID');

        var triggerVal = document.getElementById('webhookRowTrigger-' + webhookID).innerText;

        switch(triggerVal) {
          case 'Stream Start':
            triggerVal = 0;
            break;
          case 'Stream End':
            triggerVal = 1;
            break;
          case 'Stream Viewer Join':
            triggerVal = 2;
            break;
          case 'Stream Viewer Upvote':
            triggerVal = 3;
            break;
          case 'Stream Name Change':
            triggerVal = 4;
            break;
          case 'Chat Message':
            triggerVal = 5;
            break;
          case 'New Video':
            triggerVal = 6;
            break;
          case 'Video Comment':
            triggerVal = 7;
            break;
          case 'Video Upvote':
            triggerVal = 8;
            break;
          case 'Video Name Change':
            triggerVal = 9;
            break;
          case 'Channel Subscription':
            triggerVal = 10;
            break;
          case 'New User':
            triggerVal = 20;
            break;
          default:
            triggerVal = 0;
        }

        webhookName.value = document.getElementById('webhookRowName-' + webhookID).innerText;
        webhookEndpoint.value = document.getElementById('webhookRowEndpoint-' + webhookID).innerText;
        webhookHeader.value = document.getElementById('webhookRowHeader-' + webhookID).innerText;
        webhookPayload.value = document.getElementById('webhookRowPayload-' + webhookID).innerText;
        webhookReqTypeElement.value = document.getElementById('webhookRowType-' + webhookID).innerText;
        webhookTrigger.value = triggerVal;
        webhookInputAction.value = 'edit';
        webhookInputID.value = webhookID;

        $('#newWebhookModal').modal('show');
        webhookHeader.value = JSON.stringify(JSON.parse(webhookHeader.value), undefined, 2);
        webhookPayload.value = JSON.stringify(JSON.parse(webhookPayload.value), undefined, 2);
    }
</script>

<script type="text/javascript" charset="utf-8">
    socket.on('newGlobalWebhookAck', function (msg) {
        var webhookName = msg['webhookName'];
        var webhookURL = msg['requestURL'];
        var webhookHeader = msg['requestHeader'];
        var webhookPayload = msg['requestPayload'];
        var webhookRequestType = msg['requestType'];
        var webhookTrigger = msg['requestTrigger'];
        var webhookID = msg['requestID'];

        var tableRef = document.getElementById('webhookTable').getElementsByTagName('tbody')[0];

        var newRow = tableRef.insertRow(tableRef.rows.length);
        newRow.id = 'webhookTableRow-' + webhookID;

        var webhookNameCell = newRow.insertCell(0);
        var endpointURLCell = newRow.insertCell(1);
        var requestTriggerCell = newRow.insertCell(2);
        var requestTypeCell = newRow.insertCell(3);
        var requestHeaderCell = newRow.insertCell(4);
        var requestPayloadCell = newRow.insertCell(5);
        var buttonCell = newRow.insertCell(6);

        webhookNameCell.id = "webhookRowName-" + webhookID;
        endpointURLCell.id = "webhookRowEndpoint-" + webhookID;
        requestTriggerCell.id = "webhookRowTrigger-" + webhookID;
        requestTypeCell.id = "webhookRowType-" + webhookID;
        requestHeaderCell.id = "webhookRowHeader-" + webhookID;
        requestPayloadCell.id = "webhookRowPayload-" + webhookID;

        endpointURLCell.style.display = 'none';
        requestTypeCell.style.display = 'none';
        requestHeaderCell.style.display = 'none';
        requestPayloadCell.style.display = 'none';

        var buttonText = '<button type="button" class="btn btn-sm btn-warning" onclick="editWebhook(\'' + webhookID + '\')"><i class="fas fa-edit"></i></button> <button type="button" class="btn btn-sm btn-danger" onclick="deleteWebhookModal(\'' + webhookID + '\')"><i class="far fa-trash-alt"></i></button>';

        var triggerVal = 'Unknown';

        switch(webhookTrigger) {
          case 0:
            triggerVal = 'Stream Start';
            break;
          case 1:
            triggerVal = 'Stream End';
            break;
          case 2:
            triggerVal = 'Stream Viewer Join';
            break;
          case 3:
            triggerVal = 'Stream Viewer Upvote';
            break;
          case 4:
            triggerVal = 'Stream Name Change';
            break;
          case 5:
            triggerVal = 'Chat Message';
            break;
          case 6:
            triggerVal = 'New Video';
            break;
          case 7:
            triggerVal = 'Video Comment';
            break;
          case 8:
            triggerVal = 'Video Upvote';
            break;
          case 9:
            triggerVal = 'Video Name Change';
            break;
          case 'Channel Subscription':
            triggerVal = 10;
            break;
          case 20:
            triggerVal = 'New User';
            break;
          default:
            triggerVal = 'Unknown';
        }

        webhookNameCell.appendChild(document.createTextNode(webhookName));
        endpointURLCell.appendChild(document.createTextNode(webhookURL));
        requestTriggerCell.appendChild(document.createTextNode(triggerVal));
        requestTypeCell.appendChild(document.createTextNode(webhookRequestType));
        requestHeaderCell.appendChild(document.createTextNode(webhookHeader));
        requestPayloadCell.appendChild(document.createTextNode(webhookPayload));
        buttonCell.innerHTML = buttonText;

    });
    </script>

<script type="text/javascript" charset="utf-8">
    socket.on('changeGlobalWebhookAck', function (msg) {
        var webhookName = msg['webhookName'];
        var webhookURL = msg['requestURL'];
        var webhookHeader = msg['requestHeader'];
        var webhookPayload = msg['requestPayload'];
        var webhookRequestType = msg['requestType'];
        var webhookTrigger = msg['requestTrigger'];
        var webhookID = msg['requestID'];

        webhookNameCell = document.getElementById('webhookRowName-' + webhookID);
        endpointURLCell = document.getElementById('webhookRowEndpoint-' + webhookID);
        requestTriggerCell = document.getElementById('webhookRowTrigger-' + webhookID);
        requestTypeCell = document.getElementById('webhookRowType-' + webhookID);
        requestHeaderCell = document.getElementById('webhookRowHeader-' + webhookID);
        requestPayloadCell = document.getElementById('webhookRowPayload-' + webhookID);

        var triggerVal = 'Unknown';

        switch(webhookTrigger) {
          case 0:
            triggerVal = 'Stream Start';
            break;
          case 1:
            triggerVal = 'Stream End';
            break;
          case 2:
            triggerVal = 'Stream Viewer Join';
            break;
          case 3:
            triggerVal = 'Stream Viewer Upvote';
            break;
          case 4:
            triggerVal = 'Stream Name Change';
            break;
          case 5:
            triggerVal = 'Chat Message';
            break;
          case 6:
            triggerVal = 'New Video';
            break;
          case 7:
            triggerVal = 'Video Comment';
            break;
          case 8:
            triggerVal = 'Video Upvote';
            break;
          case 9:
            triggerVal = 'Video Name Change';
            break;
          case 'Channel Subscription':
            triggerVal = 10;
            break;
          case 20:
            triggerVal = 'New User';
            break;
          default:
            triggerVal = 'Unknown';
        }

        webhookNameCell.innerText = webhookName;
        endpointURLCell.innerText = webhookURL;
        requestTriggerCell.innerText = triggerVal;
        requestTypeCell.innerText = webhookRequestType;
        requestHeaderCell.innerText = webhookHeader;
        requestPayloadCell.innerText = webhookPayload;
    });
    </script>

<script>
    function openStreamDeleteModal(streamID) {
        document.getElementById('deleteStreamID').value = streamID;
        $('#deleteStreamModal').modal('show');
    }

    function deleteStream() {
        var streamID = document.getElementById('deleteStreamID').value;
        socket.emit('deleteStream', {streamID: streamID});
        var streamCard = document.getElementById('streamCard-' + streamID);
        streamCard.parentNode.removeChild(streamCard);
        document.getElementById('deleteStreamID').value = "";
    }

</script>


<script>
    var easymde1 = new EasyMDE({ autoDownloadFontAwesome: false, spellChecker: false, element: document.getElementById("serverMessage") });
</script>


<script>
$('#search').on('input', function(){
    var query = document.getElementById("search").value.toLowerCase();
    $('.searchable').each(function(){
         var $this = $(this);
         if($this.text().toLowerCase().indexOf(query) === -1)
             $this.closest('.searchable').hide();
        else $this.closest('.searchable').show();
    });
});
</script>

<script>
    $('.rangeSliderInput').on('input', function() {
      var sliderValue = $(this).val();
      if (sliderValue != "") {
        var maxValue = $(this).attr("max");
        if (sliderValue != maxValue) {
          var date = new Date(0);
          date.setSeconds(sliderValue);
          var timeString = date.toISOString().substr(11, 8);
        } else {
          timeString = "Infinite";
        }
        $(this).siblings("h3").find('.rangeSliderValue')[0].innerHTML = timeString;
      }
    });
</script>

{% endblock %}

